package com.hhh.springai_test.tasks;


import com.hhh.springai_test.config.AppConfig;
import com.hhh.springai_test.exception.BusinessException;
import com.hhh.springai_test.model.enums.BookBorrowStatusEnum;
import com.hhh.springai_test.model.po.BookBorrow;
import com.hhh.springai_test.model.po.User;
import com.hhh.springai_test.service.BookBorrowService;
import com.hhh.springai_test.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class BookTask {

    @Resource
    private BookBorrowService bookBorrowService;

    @Resource
    private UserService userService;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private AppConfig appConfig;

    @Scheduled(cron = "0 */5 * * * ?")
    public void updateBookBorrowStatus() {
        // 定时更新借阅状态
        List<BookBorrow> list = bookBorrowService.list();
        // 添加日期格式化
        java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");

        for (BookBorrow bookBorrow : list) {
            Date shouldreturntime = bookBorrow.getShouldreturntime();
            // 只有当图书过期且状态不为3时才更新状态并发送邮件
            if (shouldreturntime.before(new Date()) && bookBorrow.getStatus() != 3) {
                bookBorrow.setStatus(3);
                bookBorrowService.updateById(bookBorrow);
                // 发送邮件通知用户
                User user = userService.getById(bookBorrow.getUserid());
                String email = user.getEmail();
                String nickName = user.getNickName();
                String bookname = bookBorrow.getBookname();
                // 格式化日期
                String formattedReturnTime = dateFormat.format(bookBorrow.getShouldreturntime());
                
                String emailContent = "<div style=\"background-color: #f0f0f0; padding: 20px; font-family: Arial, sans-serif;\">\n" +
                        "    <h1 style=\"color: #800000; text-align: center; font-size: 24px;\">星轨图书借阅系统提醒</h1>\n" +
                        "    <div style=\"background-color: white; padding: 20px; border-radius: 10px; margin: 20px;\">\n" +
                        "        <p style=\"color: #800000; font-size: 16px; line-height: 1.6;\">亲爱的 <strong>" + nickName + "</strong>：</p>\n" +
                        "        <p style=\"color: #800000; font-size: 16px; line-height: 1.6;\">您借阅的图书已过期，请尽快归还，详细信息如下：</p>\n" +
                        "        <ul style=\"color: #800000; font-size: 16px; line-height: 1.6;\">\n" +
                        "            <li>借阅图书：<strong>" + bookname + "</strong></li>\n" +
                        "            <li>应还时间：<strong>" + formattedReturnTime + "</strong></li>\n" +
                        "        </ul>\n" +
                        "        <p style=\"color: #800000; font-size: 16px; line-height: 1.6;\">请尽快前往图书馆归还图书，以免影响您的借阅信用。</p>\n" +
                        "    </div>\n" +
                        "    <p style=\"color: #800000; font-size: 16px; line-height: 1.6; text-align: center;\">感谢您的理解与支持！</p>\n" +
                        "    <div style=\"text-align: center; margin-top: 20px;\">\n" +
                        "        <a href=\"http://localhost:5173/book\" style=\"background-color: #800000; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-size: 16px;\">查看借阅详情</a>\n" +
                        "    </div>\n" +
                        "</div>";
                sendEmailCode(email, emailContent);
            }
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void checkReturnTimeReminder() {
        List<BookBorrow> list = bookBorrowService.list();
        // 获取当前时间
        Date now = new Date();
        // 3天的毫秒数
        long threeDaysInMillis = 3 * 24 * 60 * 60 * 1000L;

        for (BookBorrow bookBorrow : list) {
            // 只处理状态为1（借阅中）的记录
            if (bookBorrow.getStatus() != 1) {
                continue;
            }
            Date shouldReturnTime = bookBorrow.getShouldreturntime();
            // 计算剩余时间
            long remainingTime = shouldReturnTime.getTime() - now.getTime();
            // 如果剩余时间小于3天且大于0（尚未过期）
            if (remainingTime > 0 && remainingTime <= threeDaysInMillis) {
                User user = userService.getById(bookBorrow.getUserid());
                String email = user.getEmail();
                String nickName = user.getNickName();
                String bookname = bookBorrow.getBookname();
                // 计算剩余天数
                int remainingDays = (int) (remainingTime / (24 * 60 * 60 * 1000));
                
                String emailContent = "<div style=\"background-color: #f0f0f0; padding: 20px; font-family: Arial, sans-serif;\">\n" +
                        "    <h1 style=\"color: #800000; text-align: center; font-size: 24px;\">星轨图书借阅系统提醒</h1>\n" +
                        "    <div style=\"background-color: white; padding: 20px; border-radius: 10px; margin: 20px;\">\n" +
                        "        <p style=\"color: #800000; font-size: 16px; line-height: 1.6;\">亲爱的 <strong>" + nickName + "</strong>：</p>\n" +
                        "        <p style=\"color: #800000; font-size: 16px; line-height: 1.6;\">您借阅的图书即将到期，请注意及时归还，详细信息如下：</p>\n" +
                        "        <ul style=\"color: #800000; font-size: 16px; line-height: 1.6;\">\n" +
                        "            <li>借阅图书：<strong>" + bookname + "</strong></li>\n" +
                        "            <li>应还时间：<strong>" + shouldReturnTime + "</strong></li>\n" +
                        "            <li>剩余天数：<strong>" + remainingDays + "天</strong></li>\n" +
                        "        </ul>\n" +
                        "        <p style=\"color: #800000; font-size: 16px; line-height: 1.6;\">请在到期前及时归还图书，以免影响您的借阅信用。</p>\n" +
                        "    </div>\n" +
                        "    <p style=\"color: #800000; font-size: 16px; line-height: 1.6; text-align: center;\">感谢您的配合！</p>\n" +
                        "    <div style=\"text-align: center; margin-top: 20px;\">\n" +
                        "        <a href=\"http://localhost:5173/book\" style=\"background-color: #800000; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-size: 16px;\">查看借阅详情</a>\n" +
                        "    </div>\n" +
                        "</div>";
                sendEmailCode(email, emailContent);
            }
        }
    }

    public void sendEmailCode(String toEmail, String value) {
        try {
            // 创建MimeMessage实例
            jakarta.mail.internet.MimeMessage message = javaMailSender.createMimeMessage();
            // 使用MimeMessageHelper来设置邮件的各个部分，true表示支持多部分和HTML
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            // 设置发件人邮箱地址
            helper.setFrom(appConfig.getSendUsername());
            // 设置收件人邮箱地址
            helper.setTo(toEmail);
            // 设置邮件主题
            helper.setSubject("星轨-图书借阅系统");
            // 设置邮件正文内容，第二个参数true表示这是HTML内容
            helper.setText(value, true);
            // 设置邮件发送日期
            helper.setSentDate(new Date());
            // 发送邮件
            javaMailSender.send(message);
        } catch (jakarta.mail.MessagingException e) {
            log.error("邮件发送失败", e);
            throw new BusinessException(407, "邮件发送失败");
        }
    }
}
